import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { STColumn, STData } from '@delon/abc'
import { ACLService } from '@delon/acl'
import { SettingsService } from '@delon/theme'
import { I18NService } from '@core'
import { FileUploadService } from '@shared/services/upload.service'
import { BatchImportService } from '../batch-import.service'
import { FileService } from '@shared/services/file.service'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { IBatchImportResult, IBatchQueryParams } from '@shared/interfaces/batch-import'

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: [
    '../../../shared/styles/new-page-form.less',
    './upload.component.less',
    '../../../shared/styles/table.less',
  ],
})
export class UploadComponent extends ListBaseClass<IBatchImportResult, IBatchQueryParams> implements OnInit {
  data: []
  columns: STColumn[] = []
  authorizationFileList: any
  xhr: any
  batchResult: any[]
  @ViewChild('fileUploadBook') fileUploadBook: any // 获取授权书文件上传dom
  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public settings: SettingsService,
    public aclService: ACLService,
    private uploderService: FileUploadService,
    private fileService: FileService,
    private batchImportService: BatchImportService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit(): void {
    this.initColumns()
    this.handleSearch()
  }

  handleFileUploadBook() {
    this.uploderService.handleFileUpload(this.fileUploadBook, (data: any) => {
      this.authorizationFileList = [data]
      const checkFileValid = this.validateFile({ name: data.name })
      if (checkFileValid) {
        const key = this.fileService.getFileKey({ name: data.name })
        this.authorizationFileList[0].key = key.split('.')[0] + '/batch_sample_tables.' + key.split('.')[1]
        // 向后端发起新增批导的请求 获取上传文件的地址
        this.batchImportService.uploadUrl(key).subscribe(res => {
          this.xhr = new XMLHttpRequest()
          this.xhr.open('put', res.url)
          this.xhr.send(data.Files)
          this.xhr.onreadystatechange = this.sendState.bind(this)
        })
      }
      return
    })
  }

  sendState() {
    if (this.xhr.readyState === XMLHttpRequest.DONE && this.xhr.status === 200) {
      const file = this.authorizationFileList[0]
      const params = {
        fileKey: file.key,
        fileName: file.name,
      }
      this.batchImportService.uploadSample(params).subscribe(res => {
        if (res) {
          this.loading = true
          this.handleSearch()
        }
      })
    }
  }


  queryTableDataWithParams(): void {
    this.loading = true
    this.batchImportService.sampleHistory(this.params).subscribe(this.renderList.bind(this), this.getListError.bind(this))
  }

  renderList(res): void {
    const { data, total } = res
    this.data = data
    this.total = total
    this.loading = false
  }

  validateFile(file) {
    if (file.name !== 'batch sample tables.zip') {
      this.msg.error('invalid file name')
      return false
    }
    return true
  }

  private initColumns() {
    this.columns = [
      {
        type: 'link',
        title: '序号',
        i18n: 'BATCH.HISTORY.NO',
        index: 'insCode',
        className: 'text-center',
        width: '150px',
        render: 'number',
        fixed: 'left',
      },
      {
        title: '上传时间',
        i18n: 'BATCH.IMPORT.UALOAD.TIME',
        index: 'createdAt',
        width: '200px',
        type: 'date',
        className: 'text-center',
      },
      {
        title: '上传用户',
        i18n: 'BATCH.UPLOAD.UPLOAD_USER',
        index: 'creator',
        width: '200px',
        className: 'text-center',
        fixed: 'right',
      },
    ]
  }

  customReq = (item) => {
    const index = item.file.name.lastIndexOf('.')
    // 获取文件名（.的前部分）
    const docName = item.file.name.substring(0, index)
    const checkFileValid = this.validateFile({name:  item.file.name})
    this.authorizationFileList = [item.file]
    if (checkFileValid) {
      const key = this.fileService.getFileKey({name: item.file.name})
      this.authorizationFileList[0].key = key.split('.')[0] + '/batch_sample_tables.' + key.split('.')[1]
      this.batchImportService.uploadUrl(key).subscribe(res => {
        this.xhr = new XMLHttpRequest()
        this.xhr.open('put', res.url)
        this.xhr.send(item.file)
        this.xhr.onreadystatechange = this.sendState.bind(this)
      })
    } else {
      return null
    }
  }
}
